package gggameserver.games.timelimit;

import gggameserver.games.Board;
import gggameserver.games.Player;
import gggameserver.util.GGConfiguration;

import java.util.HashMap;
import java.util.Map;

public class GGTimeLimit {

	private int move_tl = -1;
	private int game_tl = -1;

	private Map<Player, Integer> player_tl = new HashMap<Player, Integer>();

	public GGTimeLimit(Board board) {
		String s_move_tl = GGConfiguration.getProperty("game.move_timelimit");
		String s_game_tl = GGConfiguration.getProperty("game.game_timelimit");

		if (s_move_tl != null)
			move_tl = Integer.parseInt(s_move_tl);
		if (s_game_tl != null)
			game_tl = Integer.parseInt(s_game_tl);

		for (Player p : board.getPlayers())
			player_tl.put(p, game_tl);
	}

	public int getMoveTimeLimit(Player p) {
		int time = -1;
		time = pseudoMin(time, move_tl);
		time = pseudoMin(time, getPlayerTimeLeft(p));
		return time;
	}

	private int getPlayerTimeLeft(Player p) {
		if (game_tl < 0)
			return -1;
		Integer i = player_tl.get(p);
		return i.intValue();
	}

	public void setLastMoveTime(Player p, int time) {
		if (game_tl < 0)
			return;
		if (time < 0)
			return;
		Integer i = player_tl.get(p);
		player_tl.put(p, Math.max(i - time, 0));
	}

	int pseudoMin(int old_time, int new_time) {
		if (old_time < 0)
			return new_time; // old didn't exist
		if (new_time < 0)
			return old_time; // new doesn't exist
		// both exist, return smaller
		if (new_time < old_time)
			return new_time;
		return old_time;
	}

}
